package com.lz.library.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.lz.library.dialog.ProgressDialog
import com.lz.library.extension.findGenericClass

/**
 *  author: you : 2020/4/24
 */
abstract class BaseFragment<VM : BaseViewModel<*>, B : ViewDataBinding> : Fragment(), IView {

    //ViewDataBinding
    private var _binding: B? = null
    protected val binding: B get() = _binding!!

    //ViewModel
    protected lateinit var viewModel: VM
        private set

    //进度弹窗
    private val progressDialog: ProgressDialog by lazy { ProgressDialog(this.context!!) }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        init()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = initViewModel()
        lifecycle.addObserver(viewModel)
        viewModel.dialogEvent.observe(this) { if (it) showLoading() else hideLoading() }
        initObserve()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View {
        _binding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
        _binding!!.lifecycleOwner = this
        getVMVariableId()?.also { _binding!!.setVariable(it, viewModel) }
        return _binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData(savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding?.unbind()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(viewModel)
    }


    protected open fun init() = Unit

    protected open fun initObserve() = Unit

    protected open fun initData(savedState: Bundle?) = Unit

    //Binding ViewModel
    protected open fun getVMVariableId(): Int? = null

    /**
     * 默认使用activity中的ViewModelStoreOwner, override
     * @return
     */
    protected open fun initViewModel(): VM =
        ViewModelProvider(this)[javaClass.findGenericClass(BaseViewModel::class.java)!!]

    override fun showLoading() {
        if (!progressDialog.isShowing) progressDialog.show()
    }

    override fun hideLoading() {
        if (progressDialog.isShowing) progressDialog.dismiss()
    }
}